package org.niu.listnode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ReverseKGroup {
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        ListNode p = head;
        ListNode a = head;
        ListNode ans = new ListNode(-1);
        ListNode tail = ans;
        int n = 0;
        while(p!=null){
            p=p.next;
            n++;
    }
        int zu = n/k;
        List<List<Integer>> list = new ArrayList<>();
        for(int i = 0; i < zu;i++){
            List<Integer> t = new ArrayList<>();
            for(int j = 0;j < k;j++){
                t.add(a.val);
                a = a.next;
            }
            Collections.reverse(t);
            list.add(t);
        }
        List<Integer> t = new ArrayList<>();
        while(a!=null){
            t.add(a.val);
            a = a.next;
        }
        list.add(t);
        for(List<Integer> list1:list){
            for (Integer integer : list1) {
                ListNode nHead = new ListNode(integer);
                tail.next = nHead;
                tail = tail.next;
            }
        }
           return ans.next;
        }
}
